我有两个类 A 和 B。A 已将 B 声明为 friend 。在 B 中,我想在方法 func() 中实例化 A(即我试图在 B 的构造函数之外实例化 A)。令我惊讶的是,这似乎在 C++ 中是不允许的。这是代码:
class A {
public:
friend class B;
A(int x, int y) {
x_ = x;
y_ = y;
}
protected:
int x_, y_;
};
class B {
public:
B (int z) {
z_ = z;
}
void func () {
a (3,4);
}
protected:
A a;
int z_
};
我收到以下错误:
friendConstructor.cpp: In constructor ‘B::B(int)’:
friendConstructor.cpp:14:12: error: no matching function for call to ‘A::A()’
friendConstructor.cpp:14:12: note: candidates are:
friendConstructor.cpp:4:2: note: A::A(int, int)
friendConstructor.cpp:4:2: note: candidate expects 2 arguments, 0 provided
friendConstructor.cpp:1:7: note: A::A(const A&)
friendConstructor.cpp:1:7: note: candidate expects 1 argument, 0 provided
friendConstructor.cpp: In member function ‘void B::func()’:
friendConstructor.cpp:19:9: error: no match for call to ‘(A) (int, int)’
我有一种情况,我无法在 B 类的构造函数中实例化 A 类。在实例化 A 类之前,我必须等待某些事情发生。如果我想做的事情在 C++ 中是不可能的。你能推荐一个替代方案吗?
最佳答案
在 func
中,a
是一个成员变量,所以当你的B 被构建。它必须是 - 它是 B 的一部分。
您实际上正在做的是调用重载的 A::operator()
。 “a(3,4)”语法仅表示在构造函数的声明或初始化列表中“使用这些参数构造”。
您的解决方案是向 A 添加一个成员函数,以允许您分配变量或构造一个临时变量并使用赋值。
a = A(3,4);
关于c++ - 使用 Friend 类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20006595/