c++ - 为什么这个构造函数不带参数调用另一个构造函数?

标签 c++ constructor

我正在尝试创建两个简单的类,但这段代码由于某种原因无法编译。它说我调用 point::point 时没有参数,但我唯一一次调用 point::point 是在 main 函数中,我确实在那里调用了参数。

调试的时候发现是string_two_points的构造函数在调用point的构造函数。

#include <iostream>
#include <string>
using namespace std;
class point{
public:
    int x;
    int y;
    point(int x, int y): x(x),y(y){};
    point(const point & c): x(c.x), y(c.y) {}; 
    };

class string_two_points{ 
public:
    string type;
    point x;
    point y;
    string_two_points(string type, point & xc):type(type){
        x=xc;
    };
    string_two_points(string type, point & xc, point & yc):type(type){
        x=xc;
        y=yc;
    };

};

int main(){
    point a =  point(2,3);
    point b =  point(3,4);
    string_two_points x = string_two_points(string("abc"),a,b);
    return 0;
}

最佳答案

string_two_points(string type, point & xc):type(type){

此构造函数未初始化 point y,因此它通过调用默认无参数构造函数 point::point(不存在)进行默认初始化。

关于c++ - 为什么这个构造函数不带参数调用另一个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942603/

相关文章:

c++ - 如何查找/删除具有特定参数的结构 vector 元素?

c++ - 为什么GL_MAX_UNIFORM_BLOCK_SIZE的值会改变?

c++ - 引用为类成员初始化

java - 调用具有未知参数的构造函数

C# 构造函数链 - 更改执行顺序

c++ - 为什么删除后对象指针还能被操作?

C++:在进程内存中搜索

c++ - 如果 int 不是类,为什么 int x = int(5) 合法?

c++ - 将类构造函数作为方法调用

c++ - 并行与线程 - 性能