gpt4 book ai didi

在其他构造函数的调用中调用构造函数时出现 C++ 编译错误

转载 作者:行者123 更新时间:2023-11-30 03:25:03 26 4
gpt4 key购买 nike

<分区>

我有一个 C++ 代码似乎混淆了类构造函数,如 A::A(B b) 和接收函数指针的构造函数,如 A::A( B (*)())。让我解释一下:

编译以下代码:

#include <iostream>
#include <cstring>
#include <vector>

struct Item {
Item() {
std::cout << "ITEM::Normal constructor\n";
}
};

struct Container {
Container(Item i) {
std::cout << "CONTAINER::Normal constructor\n";
}

void doSomething() {
std::cout << "Do something\n";
}
};

int main() {
Container c3(Item());
return 0;
}

但是如果我添加对 B::doSomething() 的调用,就像下面的代码一样,我会得到一个我不理解的编译器错误:

#include <iostream>
#include <cstring>
#include <vector>

struct Item {
Item() {
std::cout << "ITEM::Normal constructor\n";
}
};

struct Container {
Container(Item i) {
std::cout << "CONTAINER::Normal constructor\n";
}

void doSomething() {
std::cout << "Do something\n";
}
};

int main() {
Container c3(Item());
c3.doSomething();
return 0;
}

编译错误为:

main.cpp: In function ‘int main()’:
main.cpp:23:6: error: request for member ‘doSomething’ in ‘c3’, which is of non-class type ‘Container(Item (*)())’
c3.doSomething();

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