c++ - 单独文件中的简单类和标题不起作用

标签 c++ class oop header

我目前正在学习c++一周,这是我的问题:
run.cpp

#include <iostream>
#include "Abc.h"

int main(){
    int a;
    std::cout << "Enter a : ";
    std::cin >> a;

    // Object Initialization
    Abc AbcObj();
}

header Abc.h :
#ifndef ABC_H
#define ABC_H


class Abc
{
    public:
        Abc();

    protected:

    private:
};

#endif // ABC_H

最后是我的实现用cpp文件 Abc.cpp :
#include "Abc.h"
#include <iostream>

Abc::Abc()
{
    std::cout << std::endl << "Object created ";
}

为什么我的控制台上没有输出?我希望“对象创建”应该在控制台上。这些文件位于同一目录中。

最佳答案

由于使用了不同的文件,因此不会出现错误,因此在此示例中我使用了一个文件

struct Foo
{
    int a;
    Foo()
    {
       std::cout << "Constructor called!";
    }
};

int main()
{
    Foo obj();
}
您为什么看不到该消息? You can read this thread
这里的问题是,Foo obj()被当作function declaration。要解决此问题,您需要删除()
int main()
{
    Foo obj;
} 

Constructor called!

关于c++ - 单独文件中的简单类和标题不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64765049/

相关文章:

c++ - 使用 STL sort() 对二维数组进行排序

c++ - 服务器多线程无法保存最后的套接字描述符

c++ - 将 ip 保存在转换列表中

java - 如何使用设计模式实现多级继承

PHP OOP MySQL 编程

C++ 编译器错误;我猜是命名空间问题

c++ - 如何在类中使用结构

PHP:链接方法调用

c++ - 一次对所有对象执行一个函数(没有 for 循环)

c++ - C++多态性与列表问题