c++ 中解决两个类的同名问题

最近写程序发现一个问题,如果两个头文件中定义的类名称一样,主函数如果又同时包含这两个头文件,那么就会出现编译错误,最简单的办法就是修改其中的一个类名,但有还可以利用namespace来解决:

如有头文件one.h

#pragma once
#ifndef ONE_H_
#define ONE_H_
namespace test1
{
class exmple
{
public:
	int add(int a, int b);
};
}
#endif // !ONE_H_

one.cpp

#include"one.h"
int test1::exmple::add(int a, int b)
{
	int c = a + b;
	return c;
}

two.h

#pragma once
#ifndef TWO_H_
#define TWO_H_
namespace test2
{
class exmple
{
public:
	int add(int a, int b);
};
};
#endif // 

two.cpp

#include"two.h"
int test2::exmple::add(int a, int b)
{
	int c = a * b;
	return c;
}

main.cpp

#pragma once
#include<iostream>
#include"one.h"
#include"two.h"
using namespace std;
void main()
{
	test1::exmple k;
	test2::exmple kk;
	cout<<k.add(10, 10)<<endl;
	cout << kk.add(10, 10) << endl;
}

《c++ 中解决两个类的同名问题》

上面只是举了个简单的例子,便于说明问题,重点在理解namespace 的用法!

    原文作者:zzzzjh
    原文地址: https://blog.csdn.net/zzzzjh/article/details/87901679
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞