C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?



我想拆分我的代码并添加一个函数。我写了这段代码,现在坚持简单的事情_

在我将类放在标题中后,我在 main 中出现错误,即"点" - 未知类型。如果我将所有功能放在一个文件中,则没有标题,所有功能都工作正常:

  • 问题如何将代码拆分为标题和主
  • 代码
  • 为什么我的加值函数不适用于类

谢谢!

需要更改的明文代码:

#include <iostream>
#include <cmath>
using namespace std;
class Point {
int x,y,z;
public:
Point(int a, int b, int c)
{   x=a;
y=b;
z=c;
}
void print ()
{
cout<<"The x value is : " << x << endl;
cout<<"The y value is : " << y << endl;
cout<<"The z value is : " << z << endl;
}
inline float norm ()
{
float t = x*x + y*y + z*z;
float s = sqrt(t);
return s;

}
void negate ()
{
x= x * -1; y= y * -1; z= z * -1;
}
};
int main ()
{
Point A1(1,2,3);
cout << "The function prints out: n";
A1.print ();
cout<< "The result of norm is: " << A1.norm () << endl;
A1.negate ();
cout << "The result of negate: n";
A1.print ();
return 0;
}

尝试实现这样的代码(传统方式(:

主要.cpp

#include "point.hpp"
#include <iostream>
int main() {
Point A1; // Point A1(1, 2, 3);
std::cout << "The function prints out: n";
A1.print();
std::cout << "The result of norm is: " << A1.norm() << std::endl;
A1.negate();
std::cout << "The result of negate: n";
A1.print();
return 0;
}

point.hpp: (只有原型声明(

#ifndef POINT_HEADER_INCLUDE_GUARD
#define POINT_HEADER_INCLUDE_GUARD
#include <cmath>
#include <iostream>
class Point {
int x, y, z;
public:
Point();
Point(int, int, int);
void  print();
float norm();
void  negate();
void  set();
};
#endif

点.cpp: (有在点.hpp中声明的事物的定义(

#include "point.hpp"
Point::Point() { set(); }
Point::Point(int a, int b, int c) {
x = a;
y = b;
z = c;
}
void Point::print() {
std::cout << "The x value is : " << x << std::endl;
std::cout << "The y value is : " << y << std::endl;
std::cout << "The z value is : " << z << std::endl;
}
float Point::norm() {
float t = x * x + y * y + z * z;
float s = std::sqrt(t);
return s;
}
void Point::negate() {
x = x * -1;
y = y * -1;
z = z * -1;
}
void Point::set() {
std::cout << "Please provide X,Y,Z values: ";
std::cin >> x >> y >> z;
std::cout << "The x value is : " << x << std::endl;
std::cout << "The y value is : " << y << std::endl;
std::cout << "The z value is : " << z << std::endl;
}

使用一些命令进行编译,例如g++ -o main main.cpp header.cpp -I ./.它可能会根据您的编译器而更改,但无论如何您都需要编译和链接这两个文件。

编辑:对于C++文件,首选将文件命名为与它包含的(主(类相同的名称。此外,即使类名包含大写字母,也希望将文件名保留为全小写。可以使用众所周知的缩写,和/或省略包含目录的名称,如果这会导致不必要的重复(例如,作为目录中每个文件名的公共前缀(,并且名称的其余部分足够唯一。

顺便说一句,您原始问题中的混乱根本不可重现。我们都因为using namespace std;而出错!

这些线程与此问题相关联:

  1. 如何在 c++ 中创建自己的头文件?
  2. C++我的头文件中应该包含哪些内容?

最新更新