c++命名空间代码测试

发布时间:2024年01月18日

Point.h

#pragma once
#include<iostream>
using namespace std;

namespace PointNamespace
{
	class point
	{
		double x, y, radius;
	public:
		point(double x, double y) :x(x), y(y), radius(0) {}
		~point() {}

		void setR(double& r);
		double getX();
		double getY();
		double getR();
		double area();
	};
	ostream& operator<<(ostream& os, point& p);
	point operator+(point& p1, point& p2);
	point operator-(point& p1, point& p2);
}


Point.cpp

#pragma once
#include"Point.h"
#include<math.h>
const double PI = 3.1415926;
namespace PointNamespace
{
	template <typename T>
	double ksm(const double& a, T b)
	{
		double res = 1, base = a;
		while (b)
		{
			if (b & 1)res *= base;
			b >>= 1;
			base *= base;
		}
		return res;
	}

	void point::setR(double& r)
	{
		this->radius = r;
	}
	double point::getX()
	{
		return this->x;
	}
	double point::getY()
	{
		return this -> y;
	}

	double point::getR()
	{
		return this->radius;
	}
	double point::area()
	{
		return PI*ksm(this->radius,2);
	}


}

operate.cpp

#pragma once
//#include<iostream>
#include"Point.h"
//using namespace std;

namespace PointNamespace
{
	ostream& operator<<(ostream& os, point& p)
	{
		os << "(" << p.getX() << "," << p.getY() << ")";
		return os;
	}

	point operator+(point& p1,point& p2)
	{
		return point(p1.getX() + p2.getX(), p1.getY() + p2.getY());
	}
	point operator-(point& p1, point& p2)
	{
		return point(p1.getX() - p2.getX(), p1.getY() - p2.getY());
	}
}

test.cpp

#include<iostream>
#include"Point.h"
using namespace std;
using namespace PointNamespace;

void test()
{
	point p1(3, 2);
	point p2(4, 5);
	point p3 = p1 + p2;
	cout << p1 << endl;
	cout << p3 << endl;
	point p4 = (p1 - p2);
	cout <<p4 << endl;
}

int main()
{
	test();
	return 0;
}

makefile编写

#第一版makefile
#main: main.o Point.o operate.o
#	g++ main.o Point.o operate.o -o main

#main.o:test.cpp
#	g++ -std=c++11 -Wall -Wextra -c test.cpp -g -o main.o 
#Point.o:Point.cpp
#	g++ -std=c++11 -Wall -Wextra -c Point.cpp -g
#operate.o:operate.cpp
#	g++ -std=c++11 -Wall -Wextra -c operate.cpp -g

#clean:
#	rm -rf *.o main


#第二版makefike
#CXX=g++
#CXXFLAGS=-std=c++11 -Wall -Wextra
#SRCS=main.o Point.o operate.o

#main:$(SRCS)
#	$(CXX) $(CXXFLAGS) $(SRCS) -o main
#main.o:test.cpp
#	$(CXX) $(CXXFLAGS) -c -g test.cpp -o main.o
#point.o:Point.cpp
#	$(CXX) $(CXXFLAGS) -c -g Point.cpp
#opera.o:operate.cpp
#	$(CXX) $(CXXFLAGS) -c -g operate.cpp

#clean:
#	rm -rf *.o main 



#第三版makefile
CXX=g++
CXXFLAGS=-std=c++11 -Wall -Wextra
SRCS=test.cpp Point.cpp operate.cpp
OBJS=$(SRCS:.cpp=.o)

main:$(OBJS)
	$(CXX) $(CXXFLAGS) $(OBJS) -o main
%.o:%.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

clean:
	rm -rf *.o main 

文章来源:https://blog.csdn.net/qq_58158950/article/details/135681257
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。