Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类/头文件-无法调用没有对象的成员_C++ - Fatal编程技术网

C++ 类/头文件-无法调用没有对象的成员

C++ 类/头文件-无法调用没有对象的成员,c++,C++,这段代码的基础是在一个教程中找到的,所以我不太清楚它为什么要这样做 错误: main.cpp: In function ‘int main()’: main.cpp:8:32: error: cannot call member function ‘int TestC::getAnswer()’ without object std::cout << TestC::getAnswer() << std::endl; TestC.hpp #include <iost

这段代码的基础是在一个教程中找到的,所以我不太清楚它为什么要这样做

错误:

main.cpp: In function ‘int main()’:
main.cpp:8:32: error: cannot call member function ‘int TestC::getAnswer()’ without object
std::cout << TestC::getAnswer() << std::endl;
TestC.hpp

#include <iostream>
#include "TestC.hpp"
int main()
{
    TestC(1, 1);
    std::cout << TestC::getAnswer() << std::endl;
    return 0;
}
#include "TestC.hpp"
TestC::TestC(int x, int y)
{
    gx = x;
    gy = y;
}

int TestC::getSum()
{
    return gx + gy;
}
#ifndef TestC_H
#define TestC_H

class TestC
{
    int gx;
    int gy;
public:
    TestC(int x, int y);
    int getAnswer();
};

#endif
我是这样编译的:

g++ main.cpp -o Main

您不只是通过调用构造函数来创建对象。您必须实际声明一个对象

TestC myC{1, 1};
int answer = myC.getAnswer();
因此,您的
main
函数将更改为

int main()
{
    TestC myC{1, 1};
    std::cout << myC.getAnswer() << std::endl;
    return 0;
}
intmain()
{
TestC-myC{1,1};

std::cout为了使
TestC::getAnswer()
工作,
getAnswer()
必须是
TestC
类的
static
成员。因此我将
int-getAnswer();
更改为
static int-getAnswer();
,但仍然不起作用。这两个TestC::TestC()都给了我类似的错误和TestC::getAnswer()作为未定义的引用。读了这篇文章,你应该知道事情应该是什么样子。我想我现在已经知道了。谢谢你。非常感谢。只是关于{}的一个问题,它们总是需要的,因为它是一个构造函数吗?你也可以编写
TestC myC=TestC(1,1)
这也很好。您只需要小心像
TestC myC();
这样的事情,它实际上会通过声明一个新函数而不是调用默认构造函数来生成一个函数。我只是使用初始值设定项列表语法
{}
,以确保不会遇到这种情况。