无法从头文件C ++访问主文件中的功能

时间:2012-05-14 13:32:34

标签: c++ scope

我不知道为什么我无法从头文件中访问我的.cpp文件中的clearConsole()函数,我想我说错了?如何从头文件中定位主文件?我尝试在customer.h中的addCustomer()函数中输入用户后调用clearConsole()函数。

Main.cpp的

// OTS.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

#include "customer.h"

// Clear function specific to Windows 
// Cross platform alternatives are more convoluted to reach desired effect, so have not been included
void clearConsole()
{
    #ifdef _WIN32
    system("cls");
    #endif
}

Customer.h

//customer.H
//The object class customer

   class customer
    {
    //...
    clearConsole();
    }

3 个答案:

答案 0 :(得分:4)

如果您的文件链接在一起,那么函数的前向声明就足够了。

<强> Customer.h

//customer.H
//The object class customer

void clearConsole(); // <--- declare function

class customer
{

//....

};

但这种结构看起来不对。我会在namespace内的不同标头中声明该函数,并在相应的实现文件中定义它:

<强> clearconsole.h

namespace ConsoleUtils
{
    void clearConsole();
}

<强> clearconsole.cpp

namespace ConsoleUtils
{
    void clearConsole()
    {
    }
}

答案 1 :(得分:0)

将clearConsole()方法移动到头文件中(我认为没有讨论我实际上不同意的.header文件下的实现,但无论如何......),并将系统消息更改为您需要的特定信息,如下:

#ifndef _WIN32
#include <syscall.h>
#endif

void clearConsole(){
    #ifdef _WIN32
    system("cls");
    #else
    system("clear");
    #endif
}

答案 2 :(得分:0)

我的内核中也存在这个问题,我用C,C ++和汇编语言写作。通过告诉ld命令允许使用-shared标志的共享变量和函数,我能够解决这个问题。在gcc中你会做同样的事情,因为gcc是一个链接器,程序集,c编译器和一个c ++编译器。