作为不同类上的私有成员的对象声明/初始化问题
抱歉,如果以前有人问过这个问题,我似乎找不到任何东西。我不知道如何搜索这个。
我有这样的事情:
class A {
private:
int x;
int y;
public:
A(int, int);
}
class B {
private:
A a(3, 4); // Doesn't compile because of this line
public:
B();
}
我能想到解决这个问题的唯一方法是使 a
成为指向 A
的指针,然后执行 a = new A(3, 4 );
在 B
的构造函数中。但我不希望 a
成为一个指针。
解决这个问题的正确方法是什么?
Sorry if this has been asked before, I can't seem to find anything. I'm not sure how to search for this.
I have something like this:
class A {
private:
int x;
int y;
public:
A(int, int);
}
class B {
private:
A a(3, 4); // Doesn't compile because of this line
public:
B();
}
The only way I could think to solve this was making a
a pointer to A
and then do a = new A(3, 4);
inside B
's constructor. But I don't want a
to be a pointer.
What's the correct way to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用“成员初始化列表”标记
B
的构造函数。而不是:您这样做:
或者如果构造函数是在标头中定义的:
You tag
B
's constructor with a "member initialization list". Instead of:You do this:
Or if the constructor is defined in the header:
从更广泛的意义上来说,解决方案是通过阅读一本关于 C++ 的书来学习 C++< /a>.是的,这很尖刻,但教程的重点是它们以合理的顺序引入概念,当它们告诉您有关数据成员的信息时,它们会同时告诉您如何初始化它们。
In a wider sense, the solution is to learn C++ by reading a book about it. Yes, that's snarky, but the point of tutorials is that they introduce concepts in a sensible order, and when they tell you about data members they will simultaneously tell you how to initialize them.
如果您想要使用参数 3 和 4 初始化 Ba,那么您可以在 B 的构造函数中执行此操作,例如,
If what you want is for B.a to be initialized with the arguments 3 and 4, then you do that in B's constructor, e.g.,