c++ - (C++) 得到错误:类::函数的无效使用,我一点也不知道为什么

标签 c++

我正在这个名为 Udemy 的网站上学习 C++ 类(class)。我刚刚完成了关于类(class)的视频讲座。在老师的鼓励下,我决定尝试使用类和头文件的想法。我首先创建 2 个 .cpp 文件和 1 个头文件。我在第二个 .cpp 文件中创建了一个函数,然后在头文件中为它创建了一个类,并尝试在第一个 .cpp 文件中调用它,但在第一个 .cpp 文件中出现错误:'Learn2 的无效使用: :学习2'。这是第一个 .cpp 文件:

    #include "Learn1.h"
    #include "Learn2.cpp"

    Learn2 learn2;

    int main() {

        string input;

        cout << "Would you like to see the menu of processes? (yes/no)" << endl;

        cin >> input;

        if (input == "yes"){
            showMenu();
        }
        else{
            cout << "all done here" << endl;
        }
        return 0;
    }

    void showMenu(){
        cout << "Processes: " << flush;
        cout << " Quit(4)   Edit(5)" << endl;
        int input;

        cin >> input;

        switch(input) {
        case 4:
            cout << "You selected: quit(4)" << endl;
            break;
        case 5:
            cout << "You selected: edit(5)" << endl;
            break;
        default:
            cout << "not recognized" << endl;
            learn2.Learn2();
            }
    }

这是第二个 .cpp 文件:

#include "Learn1.h"

Learn2::Learn2(){
    cout << "hi" << endl;
}

这是我的头文件(.h 文件):

 * Learn1.h
 *
 *  Created on: Nov 19, 2016
 *      Author: jacob
 */

#ifndef LEARN1_H_
#define LEARN1_H_

#include <iostream>
#include <limits.h>
#include <iomanip>

using namespace std;

class Learn1 {
public:
    Learn1();
    virtual ~Learn1();
};

void showMenu();

class Learn2 {
public:
    Learn2();
};

#endif /* LEARN1_H_ */

是的,我知道,代码有点随机,请记住,我只是在思考这个想法。

最佳答案

在名为Learn2 的类中,所有名为Learn2 的函数都是构造函数。它们只能用于构造对象,不能作为类对象的成员函数调用。

因此,

learn2.Learn2();

错了。

你可以使用

learn2 = Learn2();

构建一个全新的对象,然后将其分配给learn2

如果该类还有其他成员函数,您可以在 learn2. 上调用它们。

class Learn2 {
  public:
    Learn2();
    display() { std::cout << "In Learn2::display\n"; }
};

Learn learn2;
learn2.display();

关于c++ - (C++) 得到错误:类::函数的无效使用,我一点也不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713233/

相关文章:

c++ - 读取 ASCII 以外的字符

c++ - 同一对象的多个 shared_ptr,一个已损坏

c++ - 用 Boost::Test 模拟

c++ - 检索远程 pc Qt C++ 的 mac 地址

c++ - 如何正确使用支架封闭式引发剂?

c++ - 启动处于挂起状态的线程

c++ - 使用从具体类继承来实现纯虚方法C++

窗口内的C++输入框

c++ - CMake target_include_directories 和 target_compile_definitions 替代方案

c++ - 将文本文件的交替行分成两个不同但对应的数组 C++