c++ - 使用 Friend 类的构造函数

标签 c++ friend

我有两个类 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/

相关文章:

c++ - begin(),end() 和 cbegin() , cend() 有什么区别?

C++ 11使可变参数构造函数理解初始化列表的初始化列表

c++ - 模板类的模板友元函数

c++ - 为命名空间中的类模板重载输出运算符

c++ - Friend ostream& operator<< 无法访问私有(private)成员

c++ - C++派生类访问基类的好友运算符

c++ - 无法将函数定义与 cpp 中的现有声明相匹配

c++ - 删除双向链表中的节点 (C++)

c++ - 静态模板类的奇怪行为

c++ - 为什么优先级队列实现为二叉堆?