gpt4 book ai didi

c++ - 如何摆脱丑陋的记录

转载 作者:行者123 更新时间:2023-11-28 00:57:01 24 4
gpt4 key购买 nike

class c {
private:
int n[10];
public:
c();
~c();
int operator()(int i) { return n[i];};
};

class cc {
private:

public:
c *mass;
cc();
~cc();
c& operator*() const {return *mass;};
};
int somfunc() {
c *c1 = new c();

cc * cc1 = new cc();

(*cc1->mass)(1);



delete c1;
}

我有一个指向 cc 类的指向 c 类的指针。

有没有办法去掉这样的记录:

(*cc1->mass)(1);

然后这样写:

cc1->mass(1);

不可能吗?

最佳答案

当我看到“c++”和“运算符重载”标签时,我的脑海里响起了警报。

C++ 运算符重载很复杂,一些运算符如“()”或“->”使其变得更加困难。

我建议,在重载运算符之前,创建一个具有相同目的的全局函数或方法,测试它是否有效,然后用运算符替换它。

全局好友函数示例:

class c {
private:
int n[10];

public:
c();
~c();

// int operator()(int i) { return n[i]; }

// there is a friend global function, that when receives a "c" object,
// as a parameter, or declares a "c" object, as a local variable,
// this function, will have access to the "public" members of "c" objects,
// the "thisref" will be removed, when turned into a method
friend int c_subscript(c thisref, int i) ;
};

int c_subscript(c* thisref, int i)
{
return c->n[i];
}

int main()
{
c* objC() = new c();
// do something with "objcC"

int x = c_subscript(objC, 3);
// do something with "x"

return 0;
} // int main(...)

局部函数(“方法”)示例:

class c {
private:
int n[10];

public:
c();
~c();

// int operator()(int i) { return n[i]; }

int subscript(int i) ;
};

int c::subscript(int i)
{
return this.n[i];
}

int main()
{
c* objC() = new c();
// do something with "objcC"

int x = c->subscript(objC, 3);
// do something with "x"

return 0;
} // int main(...)

最后使用重载运算符:

class c {
private:
int n[10];

public:
c();
~c();

int subscript(int i) ;

int operator()(int i) { return this.subscript(i); }
};

int c::subscript(int i)
{
return this.n[i];
}

int main()
{
c* objC() = new c();
// do something with "objcC"

int x = c->subscript(3);
// do something with "x"

int x = c(3);
// do something with "x"

return 0;
} // int main(...)

请注意,在最后一个示例中,我为方法保留了唯一标识符。

干杯。

关于c++ - 如何摆脱丑陋的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10538995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com