【发布时间】:2020-06-30 16:05:07
【问题描述】:
首先感谢任何阅读我的问题的人,特别感谢任何可以提供建议的人。
我现在是 CS 162 的第二周,我们的教授刚刚向我们介绍了课程。遵循他的代码后,我完全无法编译或使用我创建的类。
为了理解我的问题,我创建了三个文件:tomato.h、tomato_imp.cpp 和tomato_driver.cpp。
顾名思义,tomato.h 是定义“tomato”类的头文件。
tomato_imp是实现文件,tomato_driver试图利用tomato的功能和定义来进行简单的操作。
番茄.h:
#ifndef TOMATO
#define TOMATO
class tomato
{
private:
int tweight;
public:
tomato(int weight=0);
void setTomato(int weight);
int getTomato() { return tweight}
};
#endif /*TOMATO*/
tomato_imp.cpp:
#pragma once;
#include "tomato.h"
//tomato constructor
tomato::tomato(int weight)
{
setTomato(weight);
}
// tomato member function
void tomato::setTomato(int weight)
{
tweight=weight;
}
tomato_driver.cpp:
#include <iostream>
#include "tomato.h"
int main(){
tomato john;
john(4);
cout<<tomato::john.getTomato;
}
我正在使用装有 OS X 10.15.5 的 MacBook,我正在使用 g++ 编译我的文件。
头文件编译时出现警告,clang:警告:在 C++ 模式下,将“c-header”输入视为“c++-header”,此行为已弃用 [-Wdeprecated]。
当我尝试编译实现文件时,它给了我几个错误:
- tomato_imp.cpp:5:9:错误:重新定义“番茄” 番茄::番茄(重量) ^ ./tomato.h:11:2: 注意:之前的定义在这里 番茄(重量){}; ^
- tomato_imp.cpp:7:3:错误:使用未声明的标识符“setTomato”;你是否 “番茄”是什么意思? 设置番茄(重量); ^ ./tomato.h:5:7: 注意:这里声明的“番茄” 番茄类{ ^
- tomato_imp.cpp:11:14: 错误: 'setTomato' 的外线定义不 匹配“番茄”中的任何声明 无效番茄::setTomato(int weight) ^~~~~~~~~
我不确定这些错误是怎么回事,所有三个文件都保存在同一个文件夹中。我已经注释掉#pragma 一次,它仍然发送完全相同的错误消息。
这稍微超出了我目前理解的计算机科学领域,非常感谢任何帮助。
【问题讨论】:
-
你对文件中的内容撒了谎,因为错误显示
tomato(int weight){};但你说的是tomato(int weight=0);。这些是不同的! -
一个问题是你的构造函数,从对象构造函数内部调用
setTomato是没有意义的。相反,只需使用tweight = weight。 -
您希望
john(4)做什么?既然写了它没有任何意义。 -
@user253751 哇,谢谢。我想你可能真的解决了我的问题。我有 2 个tomato.h 副本,一个是 sublime 文本文件,一个是 Xcode,位于我忘记的子目录中。清理我的文件后,我仍然收到:clang: error: linker command failed with exit code 1 (use -v to see invocation)
-
@elliptic_hyperboloid 好的,我将番茄构造函数的内容更改为 weight=weight。 john 背后的想法是 john 是一个番茄实例,我正在使用第 8 行的构造函数将 john 的权重设置为 8。感谢您的帮助。