【问题标题】:C++ Defining functions of a class compile error (Visual Studio)C ++定义类编译错误的函数(Visual Studio)
【发布时间】:2016-11-17 02:24:00
【问题描述】:

我刚刚开始分配并开始在“Distance.h”选项卡中定义类的函数,虽然我很确定我的函数已正确初始化,但我仍然收到编译器错误说“定义不是成立。”我使用了一位在线导师,他在他的电脑上运行它并没有出现任何错误,尽管他没有进一步帮助我解决这个问题。有谁知道在这种情况下我应该做什么,因为这是我唯一的计算机,或者是否有人可以告诉我我是否真的只是编码错误。

这是我的“Distance.h”:

#pragma once

class Distance
{
    private:
        long length;

    public:
        // Transformers
        void setLength(long newLength);
        void setFeet(int newFeet);

        // Observors
        long getLength();
        int getFeet();
        int getInches();
        double getLengthInFeet();
};

【问题讨论】:

  • 你也有Distance.cpp吗?
  • 您已经提供了函数的声明。编译器抱怨的是它找不到定义。声明是函数的“签名”。定义是函数的代码。
  • 到目前为止我的 distance.cpp 只是:#include "Distance.h"
  • 我的 source.cpp 是:#include using namespace std; #include "Distance.h" main() { // TODO: Define 1 Distance object: dist1 Distance dist1; // TODO: 调用 setLength 成员函数在 dist1 中存储一个 // 长度 setLength.dist1();

标签: c++ visual-studio class


【解决方案1】:

你必须定义你的类方法。例如:

#pragma once

class Distance
{
  private:
    long length;

  public:

    //Transformers
    void setLength(long newLength){
    // TODO: define your method here
    // For instance: length = newLength;
    }
    void setFeet(int newFeet){
    // TODO: define your method here
    }

    //Observors
    long getLength(){
    // TODO: define your method here
    }
    int getFeet(){
    // TODO: define your method here
    }
    int getInches(){
    // TODO: define your method here
    }
    double getLengthInFeet(){
    // TODO: define your method here
    }
};

【讨论】:

  • 补充:既然你提到你确实有一个Distance.cpp,你应该在那里写你的方法定义。
猜你喜欢
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2014-01-19
  • 1970-01-01
相关资源
最近更新 更多