//topic.h
#pragma once
#include
using namespace std;
void test001();
void test002();
void fun001(person p3);//值传递的方式给函数传值
class person {
public:
int age;
person() {
cout << "this is my introduction" << endl;
}
person(int a) {
age = a;
cout << "my named pan" << endl;
cout << "my age is" << " " << age << endl;
}
person(const person& other) {
age = other.age;
}
~person() {
cout << "ok,this is my all introduction" << endl;
}
};
//one.cpp
#include
#include
#include"topic.h"
using namespace std;
int main()
{
test002();
test001();
}
//function.cpp
#include
#include
#include"topic.h"
using namespace std;
void test001() {
person p1(18);
person p2(p1);
cout << "p2的年龄是" << p2.age;
}
void test002() {
person p3;
fun001(p3);//值传递的方式给函数传值
}
void fun001(person p3) {
cout << p3.age << endl;
}
使用环境为VS2022
我的原意是在学习构造函数以值传递的方式给函数传值,可是程序却出错,如果在函数fun001的形参里加入person p3程序报错更严重了。
报错如下:
//topic.h
#pragma once
#include<iostream>
using namespace std;
class person {
public:
int age;
person() {
cout << "this is my introduction" << endl;
}
person(int a) {
age = a;
cout << "my named pan" << endl;
cout << "my age is" << " " << age << endl;
}
person(const person& other) {
age = other.age;
}
~person() {
cout << "ok,this is my all introduction" << endl;
}
};
void test001();
void test002();
void fun001(person p3);//值传递的方式给函数传值
调一下函数声明顺序,类要先声明然后再能应用哈
在调用函数 fun001() 中,使用了值传递的方式将 person 类型的对象 p3 作为参数传入了该函数中。但是,在函数定义时,函数 fun001() 并没有接受任何参数,这就导致了编译器报错。
为解决该问题,可以在 topic.h 文件中声明 fun001() 函数时添加参数 person p3,如下所示:
void fun001(person p3);
这样,在函数定义时就可以接收一个类型为 person 的对象作为参数,对应的代码如下:
void fun001(person p3) {
cout << p3.age << endl;
}